package zhixin.Utils;

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.*;
import org.openqa.selenium.remote.Augmenter;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;

/**
 * @program: demo01
 * @description:
 * @author: 致心
 * @create: 2020-08-28 11:21
 **/
public class EleToImg {

    public static void snapshot(TakesScreenshot drivername, String filename) {
        File scrFile = drivername.getScreenshotAs(OutputType.FILE);
        try {
            System.out.println("save snapshot path is:E:/"+filename);
            FileUtils.copyFile(scrFile, new File("E:\\"+filename));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            System.out.println("Can't save screenshot");
            e.printStackTrace();
        }
        finally
        {
            System.out.println("screen shot finished");
        }
    }

    public static void snapshot2(WebDriver drivername, String filename) {
        try {
            WebDriver augmentedDriver = new Augmenter().augment(drivername);
            File screenshot = ((TakesScreenshot) augmentedDriver).getScreenshotAs(OutputType.FILE);
            File file = new File("E:\\"+filename);
            FileUtils.copyFile(screenshot, file);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            System.out.println("Can't save screenshot");
            e.printStackTrace();
        }
        finally
        {
            System.out.println("screen shot finished");
        }
    }

    public static byte[] takeScreenshot(WebDriver driver) throws IOException {
        WebDriver augmentedDriver = new Augmenter().augment(driver);
        return ((TakesScreenshot) augmentedDriver).getScreenshotAs(OutputType.BYTES);
    }

    public static BufferedImage createElementImage(WebDriver driver, WebElement webElement)
            throws IOException {
        // 获得webElement的位置和大小。
        Point location = webElement.getLocation();
        Dimension size = webElement.getSize();
        // 创建全屏截图。
        BufferedImage originalImage =
                ImageIO.read(new ByteArrayInputStream(takeScreenshot(driver)));
        // 截取webElement所在位置的子图。
        BufferedImage croppedImage = originalImage.getSubimage(
                location.getX(),
                location.getY(),
                size.getWidth(),
                size.getHeight());
        return croppedImage;
    }
}
